<template>
  <div class="choice-user-container">
    <div class="user-list" @click="handleOpen">
      <template v-if="userNames.length">
        <el-tag
          v-for="item in userNames"
          :key="item.id"
          class="tag"
          :disable-transitions="true"
          size="mini"
          type="info"
          closable
          @close="handleDelete(item)"
        >
          {{ item.name }}
        </el-tag>
      </template>
      <div v-else>请选择用户</div>
    </div>
    <BaseDialog
      title="选择审核人"
      width="500px"
      :dialog-show.sync="dialogShow"
      :footer="true"
      @submit="handleSubmit"
    >
      <el-input placeholder="请填写人员名称">
        <el-button slot="append" icon="el-icon-search" />
      </el-input>

      <div class="user-list-box">
        <el-checkbox-group v-model="checkData">
          <el-checkbox
            v-for="item in userListData"
            :key="+item.id"
            :label="+item.id"
          >
            {{ item.name }}
          </el-checkbox>
        </el-checkbox-group>
      </div>
    </BaseDialog>
  </div>
</template>

<script>
import adminApi from '@/api/admin'
export default {
  props: {
    value: {
      default: []
    }
  },
  data() {
    return {
      checkData: [],
      dialogShow: false,
      userNames: [],
      userListData: []
    }
  },
  watch: {
    value: {
      handler(val) {
        this.checkData = val.map(item => +item)
        this.getUserList('init')
      },
      deep: true,
      immediate: true
    },
    dialogShow: {
      handler(val) {
        if (val) {
          this.checkData = this.value.map(item => +item)
        }
      },
      immediate: true
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList(type) {
      const res = await adminApi.adminList()
      this.userListData = res.data
      if (type === 'init') {
        this.initUserName()
      }
    },
    handleOpen() {
      this.dialogShow = true
    },
    initUserName() {
      this.userNames = this.userListData.filter(item =>
        this.checkData.includes(+item.id)
      )
    },
    handleSubmit() {
      this.$emit('input', this.checkData)
      this.initUserName()
      this.dialogShow = false
    },
    handleDelete(row) {
      const index = this.checkData.findIndex(item => item === row.id)
      this.userNames.splice(index, 1)
      this.checkData.splice(index, 1)
      this.$emit('input', this.checkData)
    }
  }
}
</script>

<style lang="scss" scoped>
.choice-user-container {
  text-align: left;
  .tag {
    margin-right: 10px;
  }
  .user-list-box {
    padding: 20px 0;
  }
}
.user-list {
  width: 100%;
  background-color: #fff;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  color: #606266;
  display: inline-block;
  font-size: inherit;
  height: 40px;
  line-height: 40px;
  outline: 0;
  padding: 0 15px;
  cursor: pointer;
  text-align: left;
}
</style>
